import {HandleException, LoginException, ParamException} from "../common/HandleException";
import {ValidationError} from "sequelize";
import TokenExpiredError from 'jsonwebtoken/lib/TokenExpiredError'

/**
 * 异常处理中间件
 * @returns {function(...[*]=)}
 */
export default () => {
    return async (ctx, next) => {
        try {
            await next()
        } catch (err) {
            if (err instanceof ValidationError) {
                ctx.body = new ParamException(err.errors[0].message)
            } else if (err.status === 401) {
                if (err.originalError instanceof TokenExpiredError) {
                    ctx.body = new LoginException('登录已过期，请重新登录！')
                } else {
                    ctx.body = new LoginException('请先登录！')
                }
            } else if (err instanceof HandleException) {
                ctx.body = err;
            } else {
                ctx.body = new HandleException(err.code, err.msg);
            }
            console.error(err)
        }
    }
}
